package com.heima.wemedia.filter;


import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.ThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自媒体身份信息获取
 */
@Component
@WebFilter(filterName = "wmTokenFilter",urlPatterns = "/*")
public class WemediaFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //从请求头拿出用户id
        String userId = request.getHeader("userId");

        //存入ThreadLocal
        if (StringUtils.isNotBlank(userId)) {
            WmUser user = new WmUser();
            user.setId(Integer.valueOf(userId));
            ThreadLocalUtils.set(user);
        }

        try {
            filterChain.doFilter(request, response);
        } finally {
            //线程用完后删除回收
            ThreadLocalUtils.remove();
        }

    }
}
